"""
CLI主入口

提供命令行界面的主要入口点。
"""

import click
import sys
import asyncio
from pathlib import Path
from typing import Optional

from rich.console import Console
from rich.panel import Panel
from rich.text import Text
from rich.table import Table

# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent.parent
sys.path.insert(0, str(project_root))

from src.bootstrap import bootstrap_application, shutdown_application
from .commands import VideoCommand, WorkflowCommand, ProjectCommand, ConfigCommand
from .commands.segment import segment
from .commands.material import material_group
from .commands.jianying import jianying
from .commands.video_database import video_db


console = Console()


def print_banner():
    """打印应用横幅"""
    banner_text = Text()
    banner_text.append("🎬 MixVideo ", style="bold blue")
    banner_text.append("视频混剪系统", style="bold white")
    banner_text.append(" v1.0.0", style="dim")
    
    panel = Panel(
        banner_text,
        title="欢迎使用",
        title_align="center",
        border_style="blue",
        padding=(1, 2)
    )
    console.print(panel)


def print_help_info():
    """打印帮助信息"""
    table = Table(title="可用命令", show_header=True, header_style="bold magenta")
    table.add_column("命令", style="cyan", no_wrap=True)
    table.add_column("描述", style="white")
    table.add_column("示例", style="dim")
    
    table.add_row(
        "video",
        "视频处理相关操作",
        "mixvideo video scan /path/to/videos"
    )
    table.add_row(
        "workflow",
        "工作流管理和执行",
        "mixvideo workflow run my_workflow.json"
    )
    table.add_row(
        "project",
        "项目管理操作",
        "mixvideo project create 'My Project'"
    )
    table.add_row(
        "config",
        "配置管理",
        "mixvideo config show"
    )
    table.add_row(
        "segment",
        "视频切分处理",
        "mixvideo segment split video.mp4"
    )
    table.add_row(
        "material",
        "视频素材入库",
        "mixvideo material process ./商品"
    )
    table.add_row(
        "jianying",
        "剪映草稿项目管理",
        "mixvideo jianying scan ./templates"
    )
    
    console.print(table)


@click.group(invoke_without_command=True)
@click.option('--version', is_flag=True, help='显示版本信息')
@click.option('--verbose', '-v', is_flag=True, help='详细输出')
@click.option('--config', '-c', type=click.Path(exists=True), help='配置文件路径')
@click.pass_context
def main_cli(ctx, version, verbose, config):
    """
    🎬 MixVideo 视频混剪系统
    
    一个强大的视频处理和混剪工具，支持AI分类、工作流处理和剪映草稿生成。
    """
    # 设置上下文
    ctx.ensure_object(dict)
    ctx.obj['verbose'] = verbose
    ctx.obj['config'] = config
    
    if version:
        console.print("🎬 MixVideo v1.0.0", style="bold blue")
        console.print("视频混剪系统 - 基于AI的智能视频处理工具", style="dim")
        return
    
    if ctx.invoked_subcommand is None:
        print_banner()
        console.print()
        print_help_info()
        console.print()
        console.print("💡 使用 [bold cyan]mixvideo --help[/bold cyan] 查看详细帮助")
        console.print("💡 使用 [bold cyan]mixvideo <command> --help[/bold cyan] 查看命令帮助")


@main_cli.group()
@click.pass_context
def video(ctx):
    """视频处理相关操作"""
    pass


@main_cli.group()
@click.pass_context
def workflow(ctx):
    """工作流管理和执行"""
    pass


@main_cli.group()
@click.pass_context
def project(ctx):
    """项目管理操作"""
    pass


@main_cli.group()
@click.pass_context
def config(ctx):
    """配置管理"""
    pass


def setup_commands():
    """设置命令"""
    # 注册视频命令
    video_cmd = VideoCommand()
    video_cmd.register_commands(video)
    
    # 注册工作流命令
    workflow_cmd = WorkflowCommand()
    workflow_cmd.register_commands(workflow)
    
    # 注册项目命令
    project_cmd = ProjectCommand()
    project_cmd.register_commands(project)
    
    # 注册配置命令
    config_cmd = ConfigCommand()
    config_cmd.register_commands(config)

    # 注册视频切分命令
    main_cli.add_command(segment)

    # 注册视频素材入库命令
    main_cli.add_command(material_group)

    # 注册剪映草稿项目管理命令
    main_cli.add_command(jianying)

    # 注册视频数据库管理命令
    main_cli.add_command(video_db)


async def async_run_cli():
    """异步运行CLI"""
    try:
        # 初始化系统
        await bootstrap_application()

        # 设置命令
        setup_commands()

        # 运行CLI
        main_cli()

    except KeyboardInterrupt:
        console.print("\n❌ 操作被用户取消", style="yellow")
        sys.exit(1)
    except Exception as e:
        console.print(f"\n❌ 系统错误: {e}", style="red")
        sys.exit(1)
    finally:
        try:
            await shutdown_application()
        except:
            pass


def run_cli():
    """运行CLI"""
    import asyncio
    asyncio.run(async_run_cli())


if __name__ == '__main__':
    run_cli()
